package com.javachmapi.pay.modules.wxpay.service.impl;

import com.javachmapi.pay.config.ApiConfig;
import com.javachmapi.pay.config.WechatConfig;
import com.javachmapi.pay.constants.Constants;
import com.javachmapi.pay.entity.weixin.PreOrder;
import com.javachmapi.pay.modules.wxpay.service.WxPayService;
import com.javachmapi.pay.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import java.io.File;
import java.util.*;

import static com.javachmapi.pay.config.ApiConfig.UNIFIEDORDER;
import static com.javachmapi.pay.config.ApiConfig.UPFILEPATH;
import static com.javachmapi.pay.constants.Constants.SF_FILE_SEPARATOR;

/**
 * create by 宋利军
 */
@Service
public class WxPayServiceImpl implements WxPayService {

    private static final Logger logger = LoggerFactory.getLogger(WxPayServiceImpl.class);

    @Autowired
    private WechatConfig wechatConfig;

    /**
     * 调起生成支付二维码，适合PC端
     * @param preOrder 预支付订单对象
     * @return
     */
    @Override
    public String createNavite(PreOrder preOrder) {
        logger.info("订单号：{}生成微信支付码",preOrder.getOutTradeNo());
        try {
            // 1、设置预付单对象
            preOrder.setAppId(wechatConfig.getMpAppId());
            preOrder.setMchId(wechatConfig.getMchId());
            preOrder.setNonceStr(StringUtil.getRandomString(30));
            preOrder.setSpbillCreateIp("127.0.0.1");
            preOrder.setNotifyUrl(wechatConfig.getNotifyUrl());
            preOrder.setTradeType("NATIVE");

            Map<Object,Object> map=new HashMap<Object,Object>();
            map.put("appid",preOrder.getAppId());
            map.put("mch_id",preOrder.getMchId());
            map.put("nonce_str",preOrder.getNonceStr());
            map.put("body",preOrder.getBody());
            map.put("out_trade_no",preOrder.getOutTradeNo()); //商户订单号
            map.put("total_fee",String.valueOf(preOrder.getTotalFee()));
            map.put("spbill_create_ip",preOrder.getSpbillCreateIp());
            map.put("notify_url",preOrder.getNotifyUrl());
            map.put("trade_type", preOrder.getTradeType());
            System.out.println(map);
            // 2、获得签名
            String sign = Sign.getSign(map,wechatConfig.getMchKey());
            //String sign = Sign.createSign("UTF-8",map,wechatConfig.getMchKey());
            preOrder.setSign(sign);
            map.put("sign", sign);// 签名

            String requestXML = XmlUtil.genXml(map);

            // 3、调用微信统一下单地址
            String returnXml = HttpUtil.sendPost(UNIFIEDORDER,requestXML);

            // 4、XML转换为Object
            Map returnmap = XmlUtil.doXMLParse(returnXml);

            String returnCode = (String) returnmap.get("return_code");
            if("SUCCESS".equals(returnCode)){
                String resultCode = (String) returnmap.get("result_code");
                if("SUCCESS".equals(resultCode)){
                    logger.info("订单号：{}生成微信支付码成功",preOrder.getOutTradeNo());
                    String urlCode = (String) returnmap.get("code_url"); // 生成二维码
                    System.out.println(urlCode);// 生成二维码
                    File file = QRCodeUtil.encode(urlCode, UPFILEPATH, true); //生成二维码
                    System.out.println("urlCode："+urlCode);
                    System.out.println("生成二维码名称："+file.getName());
                    return UPFILEPATH+file.getName();
                }else{
                    String errCodeDes = (String) returnmap.get("err_code_des");
                    logger.info("订单号：{}生成微信支付码(系统)失败:{}",preOrder.getOutTradeNo(),errCodeDes);
                }
            }else{
                String returnMsg = (String) map.get("return_msg");
                logger.info("(订单号：{}生成微信支付码(通信)失败:{}",preOrder.getOutTradeNo(),returnMsg);
            }

        } catch (Exception e) {
            logger.error("订单号：{}生成微信支付码失败(系统异常))",preOrder.getOutTradeNo(),e);
        }
        return null;
    }

    /**
     * 授权扫码支付，适合PC端
     * @param preOrder
     * @return
     */
    @Override
    public String createJSAPI(PreOrder preOrder) {
        logger.info("订单号：{}生成微信支付码",preOrder.getOutTradeNo());
        String imgPath= Constants.QRCODE_PATH+ SF_FILE_SEPARATOR+preOrder.getOutTradeNo()+".png";
        try {
            // 1、设置预付单对象
            preOrder.setAppId(wechatConfig.getMpAppId());
            preOrder.setMchId(wechatConfig.getMchId());
            preOrder.setNonceStr(StringUtil.getRandomString(30));
            preOrder.setSpbillCreateIp("127.0.0.1");
            preOrder.setNotifyUrl(wechatConfig.getNotifyUrl());
            preOrder.setTradeType("JSAPI");

            Map<Object,Object> map=new HashMap<Object,Object>();
            map.put("appid",preOrder.getAppId());
            map.put("mch_id",preOrder.getMchId());
            map.put("nonce_str",preOrder.getNonceStr());
            map.put("body",preOrder.getBody());
            map.put("out_trade_no",preOrder.getOutTradeNo()); //商户订单号
            map.put("total_fee",String.valueOf(preOrder.getTotalFee()));
            map.put("spbill_create_ip",preOrder.getSpbillCreateIp());
            map.put("notify_url",preOrder.getNotifyUrl());
            map.put("trade_type", preOrder.getTradeType());
            map.put("openid", preOrder.getOpenid());
            System.out.println(map);
            // 2、获得签名
            String sign = Sign.getSign(map,wechatConfig.getMchKey());
            //String sign = Sign.createSign("UTF-8",map,wechatConfig.getMchKey());
            preOrder.setSign(sign);
            map.put("sign", sign);// 签名

            String requestXML = XmlUtil.genXml(map);

            // 3、调用微信统一下单地址
            String returnXml = HttpUtil.sendPost( UNIFIEDORDER,requestXML);

            // 4、XML转换为Object
            Map returnmap = XmlUtil.doXMLParse(returnXml);

            String returnCode = (String) returnmap.get("return_code");
            if("SUCCESS".equals(returnCode)){
                String resultCode = (String) returnmap.get("result_code");
                if("SUCCESS".equals(resultCode)){
                    logger.info("订单号：{}生成微信支付码成功",preOrder.getOutTradeNo());
                    String urlCode = (String) returnmap.get("code_url"); // 生成二维码
                    File file = QRCodeUtil.encode(urlCode, "C:\\Users\\Administrator\\Desktop\\", true); //生成二维码
                    System.out.println("urlCode："+urlCode);
                    System.out.println("生成二维码名称："+file.getName());
                    return urlCode;
                }else{
                    String errCodeDes = (String) returnmap.get("err_code_des");
                    logger.info("订单号：{}生成微信支付码(系统)失败:{}",preOrder.getOutTradeNo(),errCodeDes);
                }
            }else{
                String returnMsg = (String) map.get("return_msg");
                logger.info("(订单号：{}生成微信支付码(通信)失败:{}",preOrder.getOutTradeNo(),returnMsg);
            }

        } catch (Exception e) {
            logger.error("订单号：{}生成微信支付码失败(系统异常))",preOrder.getOutTradeNo(),e);
        }
        return null;
    }
}
